package com.company;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.*;
import java.io.*;


public class ReadXml {
    public static String filterSpecAttr(String getType){
        String filterSpecAttr = "(?i)^(<[^>]+\\s)("+getType+"=[\"'])([^\"']*)([\"'])([^>]*>)$";
        return filterSpecAttr;
    }

    public static String getFilterDate(String getType,String line) {
        String transform = "";
        try{
            Pattern pattern = Pattern.compile(filterSpecAttr(getType));
            Matcher matcher = pattern.matcher(line);
            boolean findStatus = matcher.find();
            if (findStatus){
                transform = matcher.group(3);
            }
        }catch (IllegalStateException e){
            return transform;
        }
        return transform;
    }

    public static void readLineFile(String filename){
        try {
            FileInputStream in = new FileInputStream(filename);
            InputStreamReader inReader = new InputStreamReader(in, "UTF-8");
            BufferedReader bufReader = new BufferedReader(inReader);
            String line = null;
            Map<String, String> map = new HashMap<>();
            String svgWidth = "";
            String svgHeight = "";
            String transformMatches = "";
            SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            System.out.println("循环开始时间"+formatter.format(new Date()));
            while((line = bufReader.readLine()) != null){
                if (!"".equals(line)) {
                    String testBeginTag = "(?i)^<(?!\\/|img|br|hr|input|link)\\w*[^>]*>$";
                    String rFilterSvg = "(?i)^<svg[^>]*>$";
                    String rFilterG = "(?i)^<g[^>]*>$";
                    String rFilterPath = "^<path[^>]*>$";
                    String rMNextTo = "(?i)(M[^L]+)$";
                    //正则匹配

                    if (Pattern.matches(testBeginTag, line) && Pattern.matches(rFilterSvg, line)) {

                        Pattern pattern = Pattern.compile(filterSpecAttr("width"));
                        Matcher matcher = pattern.matcher(line);
                        boolean b = matcher.find();
                        String xmlWidth = matcher.group(3);
                        if (xmlWidth.length() > 0) {
                            svgWidth = xmlWidth;
                        }

                        Pattern pattern2 = Pattern.compile(filterSpecAttr("height"));
                        Matcher matcher2 = pattern2.matcher(line);
                        boolean b2 = matcher2.find();
                        String xmlHeight = matcher2.group(3);
                        if (xmlHeight.length() > 0) {
                            svgHeight = xmlHeight;
                        }


                    } else if (Pattern.matches(testBeginTag, line) && Pattern.matches(rFilterG, line)) {
                        Pattern pattern = Pattern.compile(filterSpecAttr("transform"));
                        Matcher matcher = pattern.matcher(line);
                        boolean b = matcher.find();
                        String transform = matcher.group(3);
                        if (transform.length() > 0) {
                            transformMatches = transform;
                        }
                    }
                    Pattern p = Pattern.compile("^\\s*|\\s*$");
                    Matcher m = p.matcher(line);
                    line = m.replaceAll("");
                    if (Pattern.matches(testBeginTag, line) && Pattern.matches(rFilterPath, line)){
                        String colorMatches = getFilterDate("stroke", line);
                        String widthMatches = getFilterDate("stroke-width", line);
                        String dMatches = getFilterDate("d", line);
                        String fillMatches = getFilterDate("fill", line);
                        String fillRuleMatches = getFilterDate("fill-rule", line);
                        String fillOpacityMatches = getFilterDate("fill-opacity", line);
                        String strokeDashArrayMatches = getFilterDate("stroke-dasharray", line);
                        String name = "*";
                        String width = "*";
                        String fill = "*";
                        String fillRule = "*";
                        String fillOpacity = "*";
                        String strokeDashArray = "*";
                        if (!colorMatches.equals("") && colorMatches.length()>0){
                            name = colorMatches;
                        }
                        if (!widthMatches.equals("") && widthMatches.length()>0){
                            width = widthMatches;
                        }
                        if (!fillMatches.equals("") && fillMatches.length()>0){
                            fill = fillMatches;
                        }
                        if (!fillRuleMatches.equals("") && fillRuleMatches.length()>0){
                            fillRule = fillRuleMatches;
                        }
                        if (!fillOpacityMatches.equals("") && fillOpacityMatches.length()>0){
                            fillOpacity = fillOpacityMatches;
                        }
                        if (!strokeDashArrayMatches.equals("") && strokeDashArrayMatches.length()>0){
                            strokeDashArray = strokeDashArrayMatches;
                        }
                        if (dMatches.length()>0){
                            Pattern p1 = Pattern.compile(rMNextTo);
                            Matcher m1 = p1.matcher(dMatches);
                            String path = m1.replaceAll("");

//                            String[] points = path.split("(?=L|M)");
                            String[] arrStr = new String[]{name,width,fill,fillRule,fillOpacity,strokeDashArray};
                            String join_arr = String.join("_", arrStr);
                            if (map.get(join_arr)!= null && map.get(join_arr).length()>0){
                                map.put(join_arr,map.get(join_arr).concat(path));
                            }else{
                                map.put(join_arr, path);
                            }
                        }
                    }
                }
            }
            SimpleDateFormat formatter2 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            System.out.println("循环结束时间"+formatter2.format(new Date()));
            bufReader.close();
            inReader.close();
            in.close();
            //生成新的文件
            List<String> result = new ArrayList<>();
            for (String key:map.keySet()){
//                String d = map.get(key).join("");
                String[] info= key.split("_");
                List<String> listInfo = Arrays.asList(info);
                String color = listInfo.get(0);
                String width = listInfo.get(1);
                String fill = listInfo.get(2);
                String fillRule = listInfo.get(3);
                String fillOpacity = listInfo.get(4);
                String strokeDashArray = listInfo.get(5);
                List<String> svg = new ArrayList<>();

                svg.add("<path stroke-linecap=\"round\" d=\""  +map.get(key).toString()+"\"");

                if (!color.equals(new String(String.valueOf('*')))) {
                    svg.add("stroke=\""+color+"\"");
                }
                if (!width.equals(new String(String.valueOf('*')))) {
                    svg.add("stroke-width=\""+width+"\"");
                }
                if (!fill.equals(new String(String.valueOf('*')))) {
                    svg.add("fill=\""+fill+"\"");
                }
                if (!fillRule.equals(new String(String.valueOf('*')))) {
                    svg.add("fill-rule=\""+fillRule+"\"");
                }
                if (!fillOpacity.equals(new String(String.valueOf('*')))) {
                    svg.add("fill-opacity=\""+fillOpacity+"\"");
                }
                if (!strokeDashArray.equals(new String(String.valueOf('*')))) {
                    svg.add("stroke-dasharray=\""+strokeDashArray+"\"");
                }
                svg.add("></path>");
                String Join = String.join(" ",svg);
                result.add(Join);

            }
            // String.join()
            result.add(0,"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><svg xmlns=\"http://www.w3.org/2000/svg\" " +
                    "xmlns:xlink=\"http://www.w3.org/1999/xlink\" " +
                    "width=\""+svgWidth+"\""+" height=\""+svgHeight+"\""+"><g transform=\""+transformMatches+"\""+">");
            result.add("</g></svg>");
            SimpleDateFormat formatter3 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            System.out.println("写入文件开始时间"+formatter3.format(new Date()));
            String filePath = "C:\\Users\\zzsoft\\Desktop\\dxf-svg\\src\\com\\company\\1.svg";
            File file = new File(filePath);
            if (!file.exists()){
                file.createNewFile();
            }
            OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file),"utf-8");
            for (String insertData:result){
                writer.write(insertData);
            }
            writer.close();
            SimpleDateFormat formatter4 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            System.out.println("写入文件结束时间"+formatter4.format(new Date()));
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("读取" + filename + "出错！");
        }
    }
    public static void main(String[] args ){
        String filePath = "C:\\Users\\zzsoft\\Desktop\\dxf-svg\\1.svg";
        readLineFile(filePath);
    }

}